<?php

use Medoo\Medoo;
use QL\QueryList;

/**
 * https://medoo.in/api/new
 * http://www.querylist.cc/docs/guide/v4/http-client
 */

chdir(__DIR__);
require_once realpath('..') . '/vendor/autoload.php';
$config = include 'database.php';

echo '爬虫开始' . PHP_EOL;
$db = new Medoo($config);
$db->delete('tDealer', ['sBrand' => '保时捷']);

/*
$client = new GuzzleHttp\Client();

$res = $client->request('GET', 'https://www.porsche.cn/china/zh/accessoriesandservice/officialporschecentres/');

$html = (string)$res->getBody();
*/

$res = QueryList::get('https://www.porsche.cn/china/zh/accessoriesandservice/officialporschecentres/');
$html = $res->getHtml();





$content = QueryList::html($html)->find('div.b-standard-content-wrapper > p:nth-child(1)')->texts();


if (!empty($content)) {

    $content=strstr($content[0],'北京');
    //var_dump($content);die;
    $content=strstr($content,'。所有保时捷中心都是保时捷的授权网点并为中国的保时捷客户提供保时捷的产品及服务。',true);
    $content = str_replace(['，', '、', '和'], '|', $content);

    $cities = explode('|', $content);



    //var_dump($cities);die;
    foreach ($cities as $city) {
        /*
        $res = $client->get("http://api.map.baidu.com/geocoding/v3/?address={$city}&output=json&ak=YSxQwIIc3fw5XrzPADPLnP7xFbLtsMj9");

        $data = json_decode((string)$res->getBody(), true);*/

        $res = QueryList::get("http://api.map.baidu.com/geocoding/v3/?address={$city}&output=json&ak=YSxQwIIc3fw5XrzPADPLnP7xFbLtsMj9");

        $data = json_decode($res->getHtml(), true);


        if ($data['status'] === 0) {
            /*
            $res = $client->request('GET',
                'https://www.porsche.cn/all/dealer2/GetLocationsWebService.asmx/GetLocationsInStateSpecialJS?' .

                http_build_query([
                    'market' => 'china',
                    'siteId' => 'china',
                    'language' => 'zh',
                    '_locationType' => 'Search.LocationTypes.Dealer',
                    'searchMode' => 'proximity',
                    'address' => $city,
                    'state' => '',
                    'maxproximity' => '',
                    'maxnumtries' => '',
                    'maxresults' => '',
                    'searchKey' => $data['result']['location']['lat'] . '|' . $data['result']['location']['lng']
                ])
            );
            $html = (string)$res->getBody();
            */
           

            $res = QueryList::get("https://www.porsche.cn/all/dealer2/GetLocationsWebService.asmx/GetLocationsInStateSpecialJS",[
                    'market' => 'china',
                    'siteId' => 'china',
                    'language' => 'zh',
                    '_locationType' => 'Search.LocationTypes.Dealer',
                    'searchMode' => 'proximity',
                    'address' => $city,
                    'state' => '',
                    'maxproximity' => '',
                    'maxnumtries' => '',
                    'maxresults' => '',
                    'searchKey' => $data['result']['location']['lat'] . '|' . $data['result']['location']['lng']
                ]);

            $html = (string)$res->getHtml();
            //？？？？？？不进行此步，simplexml_load_string报错
            $html=ltrim($html);
            //var_dump($html);die;
            
            $xml = simplexml_load_string($html);
            /*var_dump($xml);die;
            if(is_null($xml)){
                continue;
            }*/


            //var_dump($xml);die;
            $list = $xml->listoflocations->children();
            
            //var_dump($list);die;
            
            //符号小写
            foreach ($list as $dealer) {
                $dealer = json_decode(json_encode($dealer),true);
                //var_dump($dealer);die;
                $data = [
                    'sDealerName' => $dealer['name'],
                    'nBrandID' => '',
                    'sBrand' => '保时捷',

                    'sProvince' => $dealer['statename']??$dealer['addressdata']['city'],
                    'sCity' => $dealer['addressdata']['city'],

                    'sAddress' => $dealer['addressdata']['city'] . $dealer['addressdata']['street'],
                    'sSaleCall' => $dealer['addressdata']['phone'],
                    'sLatitude' => $dealer['coordinates']['lat'],
                    'sLongitude' => $dealer['coordinates']['lng'],
                    'dUpdateTime' => Medoo::raw('now()'),
                    'sRemarks' => $dealer['id'],
                ];
                if (!$db->has('tDealer', ['sRemarks' => $dealer['id'], 'sBrand' => '保时捷',])) {
                    $db->insert('tDealer', $data);
                }

                echo "{$dealer['name']}完成" . PHP_EOL;
            }

        } else {
            echo '百度api调用出错，抓取失败' . PHP_EOL;
        }

    }
    echo '爬虫完成' . PHP_EOL;
}

